package net.ib.mtalk.sync;


import net.ib.mtalk.account.MTalkSyncServiceAdapter;
import net.ib.mtalk.constant.MTalkConstant;
import net.ib.mtalk.global.GlobalApplication;
import net.ib.mtalk.global.GlobalPreferences;
import net.ib.mtalk.network.task.AddContactsTask;
import net.ib.mtalk.util.MTalkLogWriter;
import android.accounts.Account;
import android.content.ContentResolver;
import android.content.Context;
import android.content.SyncResult;
import android.content.SyncStatusObserver;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

/**
 * App 을 실행 시키는 경우 주소록의 변경 여부를 검사하여 서버로 주소록을 전송 할지 않할지 결정한다. 
 * @author namkhoh
 *
 */
public class AsyncCheckVersion extends AsyncTask<Void, Void, Integer>{

	private Context mContext;
	private ContentResolver mResolver;
	private Handler mHandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			
		}
	};
	
	
	@Override
	protected Integer doInBackground(Void... params) {
		return ContactComparator.checkContactVersion();
	}
	
	@Override
	protected void onPostExecute(Integer result) {

		mContext = GlobalApplication.getContext();
		mResolver = mContext.getContentResolver();
		
		if ((GlobalPreferences.getUserUUID() == null) || GlobalPreferences.getContact_Version() == 0) {
			MTalkLogWriter.d("아직 가입을 하거나 첫 번째 주소록 전송이 이뤄지지 않았다.");
			// 아직 가입을 하거나 첫 번째 주소록 전송이 이뤄지지 않았다.
			return;
		}
		
		if (GlobalPreferences.getContact_Version() != result) {
			// DO sync
			MTalkLogWriter.i("Need to perform Contact Sync Opeartion " + getClass().getSimpleName());
			AddContactsTask task = new AddContactsTask(mContext, mHandler);
			task.execute();
//			Account account = new Account(GlobalPreferences.getMSISDN(), MTalkConstant.ACCOUNT_TYPE);
//			MTalkSyncServiceAdapter.performSync(mContext, 
//					account, new Bundle(), 
//					MTalkConstant.CONTACT_AUTHORITY, 
//					mResolver.acquireContentProviderClient(MTalkConstant.CONTACT_AUTHORITY), 
//					new SyncResult());
//			ContentResolver.requestSync(account, ChatONConst.CONTACT_AUTHORITY, new Bundle());
		} else{
			MTalkLogWriter.i("변경 없음 ");
		}
	}
}
